import 'package:shared_preferences/shared_preferences.dart';


class SpUtil{
  static final SpUtil _spUtil = SpUtil._internal();
  SpUtil._internal();
  factory SpUtil() => _spUtil;
  static SpUtil get instance => _spUtil;

  Function? _initCallback;
  set initCallback(Function value) {
    _initCallback = value;
  }

  SharedPreferences? _sp;
  SharedPreferences? get sp => _sp;

  Future<void> init() async{
    await SharedPreferences.getInstance().then((value) { // initialize
      _sp = value;
      if(_initCallback != null){
        _initCallback?.call();
      }
    });
  }


  void save2Sp(String key, dynamic value){
    switch(value.runtimeType){
      case const (List<String>):{
        _sp?.setStringList(key, value);
        break;
      }
      case const (String):{
        _sp?.setString(key, value);
        break;
      }
      case const (int):{
        _sp?.setInt(key, value);
        break;
      }
      case const (double):{
        _sp?.setDouble(key, value);
        break;
      }
      case const (bool):{
        _sp?.setBool(key, value);
        break;
      }
    }
  }

  int? getInt(String key){
    return _sp?.getInt(key);
  }

  double? getDouble(String key){
    return _sp?.getDouble(key);
  }

  String? getString(String key){
    return _sp?.getString(key);
  }

  bool? getBool(String key){
    return _sp?.getBool(key);
  }

  List<String>? getStringList(String key){
    return _sp?.getStringList(key);
  }

  Future<bool?> remove(String key) async{
    return await _sp?.remove(key);
  }

}